package
{
	import flash.geom.Point;
	
	import starling.display.DisplayObject;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;

	public class Game extends Sprite
	{
		private var cusomSprite:CustomSprite;
		private var mouseX:Number = 0;
		private var mouseY:Number = 0;
		
		public function Game()
		{
			addEventListener(Event.ADDED_TO_STAGE, onAdded); 
		}
		
		private function onAdded($e:Event):void
		{
			cusomSprite = new CustomSprite(200, 200);
			cusomSprite.x = (stage.stageWidth - cusomSprite.width >> 1) + (cusomSprite.width >> 1);
			cusomSprite.y = (stage.stageHeight - cusomSprite.height >> 1) + (cusomSprite.height >> 1);
			addChild(cusomSprite);
			stage.addEventListener(TouchEvent.TOUCH, onTouch);
			stage.addEventListener(Event.ENTER_FRAME, onFrame);
			cusomSprite.addEventListener(TouchEvent.TOUCH, onTouchedSprite);
		}
		
		private function onFrame($e:Event):void
		{
			cusomSprite.x -= (cusomSprite.x - mouseX) * .1;
			cusomSprite.y -= (cusomSprite.y - mouseY) * .1;
			cusomSprite.update();
		}
		
		private function onTouch($e:TouchEvent):void
		{		
			trace($e);
			var touch:Touch = $e.getTouch(stage);
			//마우스 클릭따라 움직이기			
			var pos:Point = touch.getLocation(stage);
			mouseX = pos.x;
			mouseY = pos.y;
		}
		
		
		private function onTouchedSprite($e:TouchEvent):void
		{		
			trace($e);
			var touch:Touch = $e.getTouch(stage);
			var clicked:DisplayObject = $e.currentTarget as DisplayObject;
			if(touch.phase == TouchPhase.ENDED)
			{
				removeChild(clicked);
				trace ("1", clicked.hasEventListener($e.type) ); 
				
				if(clicked.hasEventListener($e.type))
				{
					clicked.dispose();		
					trace ("2", clicked.hasEventListener($e.type) ); 
				}
				//스테이지의 모든 이벤트까지 없애기
				stage.removeEventListeners();
			}
		}
	}
}